//
//  SISSKPIEnrollViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/10/15.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSKPIEnrollViewController.h"
#import "SWForm.h"
#import "SISSKPIEnrollFinishResultViewController.h"
#import "SISSJsonRequestNetworkingManager+Registration.h"
#import "SISSDatePickerView.h"
#import "SISSFilterChooseBaseViewController.h"
#import "SISSRoomChooseViewController.h"
#import "SISSFilterOrganChooseViewController.h"

#import <ContactsUI/ContactsUI.h>
#import <Contacts/Contacts.h>

#import "UIView+frameAdjust.h"

#import "SISSAddressPickerView.h"

#import "SISSKPIDetailModel.h"

@interface SISSKPIEnrollViewController ()<SISSDatePickerViewDelegate,CNContactPickerDelegate>

@property (weak, nonatomic) UIButton *submitButton;
@property (weak, nonatomic) UILabel *bottomTipLabel;

@property (weak, nonatomic) SWFormItem *businessTypeItem;

@property (weak, nonatomic) SWFormItem *certificateNoItem;
@property (weak, nonatomic) SWFormItem *dealTimeItem;
@property (weak, nonatomic) SWFormItem *contractNoItem;

@property (weak, nonatomic) SWFormItem *regionItem;
@property (weak, nonatomic) SWFormItem *communityItem;
@property (weak, nonatomic) SWFormItem *buildingItem;
@property (weak, nonatomic) SWFormItem *roomItem;
@property (weak, nonatomic) SWFormItem *organNameItem;
@property (weak, nonatomic) SWFormItem *nameItem;
@property (weak, nonatomic) SWFormItem *mobileItem;


/// 栋列表
@property (strong, nonatomic) NSArray<SISSBuildingNumberModel *> *buildingArr;
/// 选中的栋modl
@property (strong, nonatomic) SISSBuildingNumberModel *buildingNumberModel;
/// 选中的房号model
@property (strong, nonatomic) SISSRoomNumberModel *roomNumberModel;

@property (copy, nonatomic) NSString *city;
@property (copy, nonatomic) NSString *district;

/// 是否修改了地区
@property (assign, nonatomic) BOOL isChangedRegion;

@end

@implementation SISSKPIEnrollViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 添加左侧的关闭按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"关闭"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    [self initUI];
    self.city = @"440300";
    self.district = @"440304";
    
    if (self.KPIDetailModel) {
//        self.city = self.KPIDetailModel.city;
//        self.district = self.KPIDetailModel.district;
        self.businessTypeItem.info = self.KPIDetailModel.businessType;
        [self showWithSelectStr:self.KPIDetailModel.businessType];
        self.certificateNoItem.info = self.KPIDetailModel.certificateNum;
        if ([self.KPIDetailModel.businessType isEqualToString:@"租赁"]) {
            self.contractNoItem.info = self.KPIDetailModel.contractNum;
        } else if ([self.KPIDetailModel.businessType isEqualToString:@"买卖"]) {
            self.contractNoItem.info = [self substring:self.KPIDetailModel.contractNum fromStr:@"深(" endStr:@")房现买字("];
            self.contractNoItem.secondInfo = [self substring:self.KPIDetailModel.contractNum fromStr:@"房现买字(" endStr:@")第"];
            
            self.contractNoItem.thirdInfo = [self substring:self.KPIDetailModel.contractNum fromStr:@")第" endStr:@"号"];
        }
        
        self.dealTimeItem.info = self.KPIDetailModel.dealTime.length > 0 ? [NSDate yyr_stringToString:self.KPIDetailModel.dealTime] : @"";
        self.regionItem.info = [NSString stringWithFormat:@"%@ %@",self.KPIDetailModel.city,self.KPIDetailModel.district];
        self.communityItem.info = self.KPIDetailModel.neighbourhood;
        self.buildingItem.info = self.KPIDetailModel.b_num;
        self.roomItem.info = self.KPIDetailModel.d_num;
        self.organNameItem.info = self.KPIDetailModel.organName;
        self.nameItem.info = self.KPIDetailModel.name;
        self.mobileItem.info = self.KPIDetailModel.mobile;
        [self.formTableView reloadData];
    }
}

- (NSString *)substring:(NSString *)string fromStr:(NSString *)fromStr endStr:(NSString *)endStr {
    NSRange startRange = [string rangeOfString:fromStr];
    NSRange endRange = [string rangeOfString:endStr];
    NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
    return [string substringWithRange:range];
}

- (void)back {
    NSString *title = @"放弃";
    NSString *message = self.KPIDetailModel ? @"修改还未完成，您确定放弃吗？" : @"登记还未完成，您确定放弃吗？";
    [self alertConfirmCacellActionAlertWithTitle:title message:message];
}

- (void)setIsContinueEnroll:(BOOL)isContinueEnroll {
    _isContinueEnroll = isContinueEnroll;
    if (isContinueEnroll) {
        
//        self.businessTypeItem.info = @"";
//        self.submitButton.backgroundColor = SECONDARY_TEXT_COLOR;
//        self.submitButton.userInteractionEnabled = NO;
//        self.bottomTipLabel.hidden = YES;
//        NSMutableArray *items = [NSMutableArray array];
//        SWFormSectionItem *beforeSectionItem = (SWFormSectionItem*)self.mutableItems.firstObject;
//        SWFormItem *businessTypeItem = beforeSectionItem.items.firstObject;
//        [items addObject:businessTypeItem];
//        [self.mutableItems removeAllObjects];
//        SWFormSectionItem *sectionItem = [SWFormSectionItem sw_sectionItem:items];
//        [self.mutableItems addObject:sectionItem];
        
            self.certificateNoItem.info = @"";
            self.dealTimeItem.info = @"";
            self.contractNoItem.info = @"";
            self.contractNoItem.secondInfo = @"";
            self.contractNoItem.thirdInfo = @"";
            self.communityItem.info = @"";
            self.buildingItem.info = @"";
            self.roomItem.info = @"";
            self.nameItem.info = @"";
            self.mobileItem.info = @"";
        [self.formTableView reloadData];
    }

}


- (void)submitButtonClickAction {
    // 这里只是简单描述校验逻辑，可根据自身需求封装数据校验逻辑
    [SWFormHandler jyt_checkFormNullDataWithWithDatas:self.mutableItems success:^{
        
        NSString *contractNum = @"";
        NSString *community = @"";
        NSString *building = @"";
        NSString *room = @"";
        NSString *organName = @"";
        NSString *name = @"";
        NSString *mobile = @"";
        NSString *certificateNum = @"";
        if ([self.businessTypeItem.info isEqualToString:@"租赁"]) {
            //            self.city = self.KPIDetailModel.city;
            //            self.district = self.KPIDetailModel.district;
            contractNum = self.contractNoItem.info;
            name = self.nameItem.info;
            mobile = self.mobileItem.info;
            if (self.dealTimeItem.info.length > 0 && [PublicUtil compareOneDate:[NSDate date] withAnotherDate:[PublicUtil getNSDateFromSimpleDateString:self.dealTimeItem.info]] == NSOrderedAscending) {
                [self alertWithMessage:@"成交日期不能大于当前时间"];
                return ;
            }
            if (![NSString checkTelNumber:mobile]) {
                [self alertWithMessage:@"您输入的手机号码格式不正确"];
                return;
            }
        } else if ([self.businessTypeItem.info isEqualToString:@"买卖"]) {
            //            self.city = @"";
            //            self.district = @"";
            certificateNum = self.certificateNoItem.info;
            contractNum = [NSString stringWithFormat:@"深(%@)房现买字(%@)第%@号",self.contractNoItem.info,self.contractNoItem.secondInfo,self.contractNoItem.thirdInfo];
        }
        community = self.communityItem.info;
        building = self.buildingItem.info;
        room = self.roomItem.info;
        organName = self.organNameItem.info;
        NSString *dealTime = self.dealTimeItem.info.length > 0 ? [self.dealTimeItem.info stringByReplacingOccurrencesOfString:@"-" withString:@"/"] : @"";
        if (self.KPIDetailModel && !self.isChangedRegion) {
            self.city = @"";
            self.district = @"";
        }
        NSDictionary *parameters = @{
                                     @"id": self.KPIDetailModel ? self.KPIDetailModel.ID : @"",
                                     @"spId": [SISSUserAccount shared].spId,
                                     @"businessType": self.businessTypeItem.info,
                                     @"certificateNum": certificateNum,
                                     @"contractNum": contractNum,
                                     @"dealTime": dealTime,
                                     @"province": @"440000",
                                     @"city": self.city,
                                     @"district": self.district,
                                     @"neighbourhood": community,
                                     @"b_num": building,
                                     @"d_num": room,
                                     @"organName": organName,
                                     @"name": name,
                                     @"mobile": mobile
                                     };
        if (self.KPIDetailModel) { // 修改
            [kJsonRequestNetworkingManager updateAchievementApplyWithParameters:parameters successBlock:^(id responseObject) {
                if ([responseObject[@"code"] integerValue] == 200) {
                    
                    NSLog(@"%@",responseObject[@"data"]);
                    //                [self alertWithMessage:@"已提交，待机构审核"];
                    SISSKPIEnrollFinishResultViewController *vc = [[SISSKPIEnrollFinishResultViewController alloc] init];
                    vc.ID = responseObject[@"data"];
                    vc.isChange = YES;
                    [self.navigationController pushViewController:vc animated:YES];
                                   
                } else {
                    [self alertActionAlertWithTitle:@"提示" message:responseObject[@"message"]];
                }
            } failed:^(NSError *error) {
                 NSLog(@"%@",error);
            }];
        } else {
            [kJsonRequestNetworkingManager insertAchievementApplyWithParameters:parameters successBlock:^(id responseObject) {
                if ([responseObject[@"code"] integerValue] == 200) {
                    
                    NSLog(@"%@",responseObject[@"data"]);
                    //                [self alertWithMessage:@"已提交，待机构审核"];
                    SISSKPIEnrollFinishResultViewController *vc = [[SISSKPIEnrollFinishResultViewController alloc] init];
                    vc.ID = responseObject[@"data"];
                    [self.navigationController pushViewController:vc animated:YES];
                } else {
                    [self alertActionAlertWithTitle:@"提示" message:responseObject[@"message"]];
                }
            } failed:^(NSError *error) {
                NSLog(@"%@",error);
            }];
        }
        
    } failure:^(NSString *error) {
        NSLog(@"error====%@",error);
        [self alertWithMessage:error];
    }];
}

- (void)selectCommunityWithItem {
    
    NSArray *arr = @[@"租赁", @"买卖"];
    
    [self alertWithActionSheetTitles:arr cancelStr:@"取消" selectBlock:^(NSInteger index, NSString * _Nullable selectStr) {
        [self showWithSelectStr:selectStr];
    }];
}

- (void)showWithSelectStr:(NSString *)selectStr {
    self.businessTypeItem.info = selectStr;
    self.submitButton.backgroundColor = MAIN_COLOR;
    self.submitButton.userInteractionEnabled = YES;
    self.bottomTipLabel.hidden = NO;
    
    NSMutableArray *items = [NSMutableArray array];
    SWFormSectionItem *beforeSectionItem = (SWFormSectionItem*)self.mutableItems.firstObject;
    SWFormItem *businessTypeItem = beforeSectionItem.items.firstObject;
    [items addObject:businessTypeItem];
    [self.mutableItems removeAllObjects];
    
    if ([selectStr isEqualToString:@"租赁"]) {
        [self rentWithItems:items];
    } else if ([selectStr isEqualToString:@"买卖"]) {
        [self sellWithItems:items];
    }
    [self.formTableView reloadData];
}

- (void)rentWithItems:(NSMutableArray *)items {
    
    SWFormItem *regionItem = [SWFormItem sw_itemWithTitle:@"地区(限广东省)：" info:@"深圳市 福田区" itemType:SWFormItemTypeSelect editable:NO required:YES keyboardType:UIKeyboardTypeDefault];
    regionItem.itemSelectCompletion = ^(SWFormItem *item) {
        [self selectRegionWithItem:item];
    };
    [items addObject:regionItem];
    self.regionItem = regionItem;
    
    SWFormItem *communityItem = [SWFormItem sw_itemWithTitle:@"小区：" info:@"" itemType:SWFormItemTypeSelect editable:NO required:YES keyboardType:UIKeyboardTypeDefault];
    communityItem.itemSelectCompletion = ^(SWFormItem *item) {
        [self selectCommunityWithItem:item];
    };
    [items addObject:communityItem];
    self.communityItem = communityItem;
    
    SWFormItem *buildingItem = [SWFormItem sw_itemWithTitle:@"楼栋：" info:@"" itemType:SWFormItemTypeSelect editable:NO required:YES keyboardType:UIKeyboardTypeDefault];
    buildingItem.itemSelectCompletion = ^(SWFormItem *item) {
        [self selectBuildingWithItem:item];
    };
    [items addObject:buildingItem];
    self.buildingItem = buildingItem;
    
    
    SWFormItem *roomItem = [SWFormItem sw_itemWithTitle:@"房号：" info:@"" itemType:SWFormItemTypeSelect editable:NO required:YES keyboardType:UIKeyboardTypeDefault];
    roomItem.itemSelectCompletion = ^(SWFormItem *item) {
        [self selectRoomWithItem:item];
    };
    //    room.unit = @"";
    [items addObject:roomItem];
    self.roomItem = roomItem;
    
    NSMutableArray *secondItems = [NSMutableArray array];
    
    SWFormItem *contractNoItem = [SWFormItem sw_itemWithTitle:@"机构合同编号：" info:@"" itemType:SWFormItemTypeInput editable:YES required:YES keyboardType:UIKeyboardTypeDefault];
    contractNoItem.placeholder = @"请输入机构内部租赁合同编号";
    [secondItems addObject:contractNoItem];
    self.contractNoItem = contractNoItem;
    
    SWFormItem *organNameItem = [SWFormItem sw_itemWithTitle:@"合同落款机构：" info:@"" itemType:SWFormItemTypeSelect editable:NO required:YES keyboardType:UIKeyboardTypeDefault];
    organNameItem.placeholder = @"请选择租赁合同落款机构名称";
    organNameItem.itemSelectCompletion = ^(SWFormItem *item) {
        [self selectOrganWithItem:item];
    };
    [secondItems addObject:organNameItem];
    self.organNameItem = organNameItem;
    
    SWFormItem *dealTimeItem = [SWFormItem sw_itemWithTitle:@"成交日期：" info:@"" itemType:SWFormItemTypeSelect editable:NO required:YES keyboardType:UIKeyboardTypeDefault];
    dealTimeItem.itemSelectCompletion = ^(SWFormItem * _Nonnull item) {
        [self selectDealTimeWithItem];
    };
    [secondItems addObject:dealTimeItem];
    self.dealTimeItem = dealTimeItem;
    
    NSMutableArray *thirdItems = [NSMutableArray array];
    
    SWFormItem *nameItem = [SWFormItem sw_itemWithTitle:@"租客（业主）姓名：" info:@"" itemType:SWFormItemTypeInput editable:YES required:YES keyboardType:UIKeyboardTypeDefault];
    [thirdItems addObject:nameItem];
    self.nameItem = nameItem;
    
    SWFormItem *mobileItem = [SWFormItem sw_itemWithTitle:@"租客（业主）电话：" info:@"" itemType:SWFormItemTypeInputSelect editable:YES required:YES keyboardType:UIKeyboardTypeDefault];
    mobileItem.images = @[[UIImage imageNamed:@"tongxunlu"]];
    mobileItem.itemSelectCompletion = ^(SWFormItem * _Nonnull item) {
        [self selectMobileItemWithItem];
    };
    [thirdItems addObject:mobileItem];
    self.mobileItem = mobileItem;
    
    SWFormSectionItem *sectionItem = [SWFormSectionItem sw_sectionItem:items];
    SWFormSectionItem *secondSectionItem = [SWFormSectionItem sw_sectionItem:secondItems];
    secondSectionItem.headerHeight = 22;
    SWFormSectionItem *thirdSectionItem = [SWFormSectionItem sw_sectionItem:thirdItems];
    thirdSectionItem.headerHeight = 22;
    [self.mutableItems addObject:sectionItem];
    [self.mutableItems addObject:secondSectionItem];
    [self.mutableItems addObject:thirdSectionItem];
}

- (void)sellWithItems:(NSMutableArray *)items {
    SWFormItem *certificateNoItem = [SWFormItem sw_itemWithTitle:@"不动产权证书编码：" info:@"" itemType:SWFormItemTypeInput editable:YES required:YES keyboardType:UIKeyboardTypeDefault];
    
    [items addObject:certificateNoItem];
    self.certificateNoItem = certificateNoItem;
    
    SWFormItem *communityItem = [SWFormItem sw_itemWithTitle:@"小区：" info:@"" itemType:SWFormItemTypeSelect editable:NO required:YES keyboardType:UIKeyboardTypeDefault];
    communityItem.itemSelectCompletion = ^(SWFormItem *item) {
        [self selectCommunityWithItem:item];
    };
    [items addObject:communityItem];
    self.communityItem = communityItem;
    
    SWFormItem *buildingItem = [SWFormItem sw_itemWithTitle:@"楼栋：" info:@"" itemType:SWFormItemTypeSelect editable:NO required:YES keyboardType:UIKeyboardTypeDefault];
    buildingItem.itemSelectCompletion = ^(SWFormItem *item) {
        [self selectBuildingWithItem:item];
    };
    [items addObject:buildingItem];
    self.buildingItem = buildingItem;
    
    SWFormItem *roomItem = [SWFormItem sw_itemWithTitle:@"房号：" info:@"" itemType:SWFormItemTypeSelect editable:NO required:YES keyboardType:UIKeyboardTypeDefault];
    roomItem.itemSelectCompletion = ^(SWFormItem *item) {
        [self selectRoomWithItem:item];
    };
    //    room.unit = @"";
    [items addObject:roomItem];
    self.roomItem = roomItem;
    
    SWFormItem *organNameItem = [SWFormItem sw_itemWithTitle:@"网签机构名称：" info:@"" itemType:SWFormItemTypeSelect editable:NO required:YES keyboardType:UIKeyboardTypeDefault];
    organNameItem.placeholder = @"请选择买卖合同网签落款机构名称";
    organNameItem.itemSelectCompletion = ^(SWFormItem *item) {
        [self selectOrganWithItem:item];
    };
    [items addObject:organNameItem];
    self.organNameItem = organNameItem;
    
    SWFormSectionItem *sectionItem = [SWFormSectionItem sw_sectionItem:items];

    NSMutableArray *secondItems = [NSMutableArray array];
    SWFormItem *contractNoItem = [SWFormItem sw_itemWithTitle:@"政府网签买卖合同编号：" info:@"" itemType:SWFormItemTypeKPIContractNoInput editable:YES required:NO keyboardType:UIKeyboardTypeDefault];
    [secondItems addObject:contractNoItem];
    self.contractNoItem = contractNoItem;
    
    SWFormSectionItem *secondSectionItem = [SWFormSectionItem sw_sectionItem:secondItems];
    secondSectionItem.headerHeight = 44;
    secondSectionItem.headerView = [self sectionHeaderView];
    
    [self.mutableItems addObject:sectionItem];
    [self.mutableItems addObject:secondSectionItem];
    [self.formTableView layoutIfNeeded];
}


- (void)selectRegionWithItem:(SWFormItem *)item {

    SISSAddressPickerView *addressPicker = [[SISSAddressPickerView alloc] initWithDefaultValues:@[self.KPIDetailModel ? self.KPIDetailModel.city : @"深圳市",self.KPIDetailModel ? self.KPIDetailModel.district : @"福田区"]];
    addressPicker.selectedItemBlock = ^(NSArray *addressArr) {
       
        self.city = [addressArr objectAtIndex:0][@"value"];
        self.district = [addressArr objectAtIndex:1][@"value"];
        NSString *city = [addressArr objectAtIndex:0][@"text"];
        NSString *district = [addressArr objectAtIndex:1][@"text"];
        self.regionItem.info = [NSString stringWithFormat:@"%@ %@",city,district];
        self.isChangedRegion = YES;
        [self.formTableView reloadData];
    };
}

- (void)selectCommunityWithItem:(SWFormItem *)item {
    
    SISSFilterChooseBaseViewController *vc = [[SISSFilterChooseBaseViewController alloc] init];
    vc.title = @"小区选择";
    vc.placeholder = @"请输入小区名称";
    vc.selectBlock = ^(NSString *tiltle) {
        if (![tiltle isEqualToString:self.communityItem.info]) {
            self.buildingItem.info = @"";
            self.roomItem.info = @"";
        }
        self.communityItem.info = tiltle;
        
        [kJsonRequestNetworkingManager requestBuildingResourceWithCommunityName:tiltle successBlock:^(NSArray<SISSBuildingNumberModel *> *buildingArr) {
            
            self.buildingArr = buildingArr;
            
        } failed:^(NSError *error) {
            NSLog(@"%@",error);
        }];
        [self.formTableView reloadData];
    };
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)selectBuildingWithItem:(SWFormItem *)item {
    
    if (self.communityItem.info.length <= 0) {
        [self alertActionAlertWithTitle:@"提示" message:@"请先选择小区信息"];
        return;
    }
    
    SISSFilterChooseBaseViewController *vc = [[SISSFilterChooseBaseViewController alloc] init];
    vc.isBuildingIn = YES;
    vc.title = @"栋号选择";
    vc.dataSource = self.buildingArr;
    vc.placeholder = @"未找到您的楼栋，请输入栋号";
    vc.selectBuildingBlock = ^(SISSBuildingNumberModel *model) {
        if (![model.bnum isEqualToString:self.buildingItem.info]) {
            self.roomItem.info = @"";
        }
        self.buildingItem.info = model.bnum;
        self.buildingNumberModel = model;
        [self.formTableView reloadData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)selectRoomWithItem:(SWFormItem *)item {
    
    if (self.communityItem.info.length <= 0) {
        [self alertActionAlertWithTitle:@"提示" message:@"请先选择小区信息"];
        return;
    }
    
    if (self.buildingItem.info.length <= 0) {
        [self alertActionAlertWithTitle:@"提示" message:@"请先选择楼栋信息"];
        return;
    }
    
    SISSRoomChooseViewController *vc = [[SISSRoomChooseViewController alloc] init];
    vc.title = @"房号选择";
    vc.buildingId = self.buildingNumberModel.dongId;
    //    vc.buildingId = @"7708";
    vc.selectBlock = ^(SISSRoomNumberModel *roomNumberModel) {
        self.roomNumberModel = roomNumberModel;
        self.roomItem.info = roomNumberModel.dnum;
        [self.formTableView reloadData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)selectOrganWithItem:(SWFormItem *)item {
    
    SISSFilterOrganChooseViewController *vc = [[SISSFilterOrganChooseViewController alloc] init];
    if ([self.businessTypeItem.info isEqualToString:@"租赁"]) {
        vc.title = @"租赁合同落款机构名称";
        vc.placeholder = @"请输入机构内部租赁合同落款机构名称";
    } else if ([self.businessTypeItem.info isEqualToString:@"买卖"]) {
        vc.title = @"买卖合同网签落款机构名称";
        vc.placeholder = @"请输入买卖合同网签落款机构名称";
    }
    vc.selectBlock = ^(NSString *tiltle) {
        
        self.organNameItem.info = tiltle;
        
        [self.formTableView reloadData];
    };
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)selectDealTimeWithItem {
    SISSDatePickerView *datePickerView = [[SISSDatePickerView alloc] initWithType:UIDatePickerModeDate title:@"成交日期"];
    [datePickerView setNowTime:[NSDate date]];
    [datePickerView setMaximumDate:[NSDate date]];
    datePickerView.delegate = self;
}

- (void)selectMobileItemWithItem {
    
    CNContactPickerViewController *contactVC = [[CNContactPickerViewController alloc] init];
    contactVC.delegate = self;
    contactVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:contactVC animated:YES completion:nil];
}

#pragma mark - CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    for (CNLabeledValue *labeledValue in contact.phoneNumbers){
        
        CNPhoneNumber *phoneValue = labeledValue.value;
        NSString * phoneNumber = phoneValue.stringValue;
        NSLog(@"number: %@",phoneNumber);
        NSString *phoneNum = [self phoneNumberFormat:phoneNumber];
        self.mobileItem.info = phoneNum;
        [self.formTableView reloadData];
    }
}


// 通讯录手机号转换纯数字
- (NSString *)phoneNumberFormat:(NSString *)phoneNum{
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:@"[^\\d]" options:0 error:NULL];
    phoneNum = [regular stringByReplacingMatchesInString:phoneNum options:0 range:NSMakeRange(0, [phoneNum length]) withTemplate:@""];
    return phoneNum;
}


#pragma mark - SISSDatePickerViewDelegate 选择时间后赋值
- (void)determine:(SISSDatePickerView *)choose date:(NSDate *)date {
    
    NSString *timeStr = [NSDate yyr_dateToString:date withDateFormat:@"yyyy-MM-dd"];
    NSLog(@"determine  %@",timeStr);
    self.dealTimeItem.info = timeStr;
    [self.formTableView reloadData];
}

- (void)changeTime:(SISSDatePickerView *)choose date:(NSDate *)date {
    
    NSString *timeStr = [choose stringFromDate:date];
    NSLog(@"changeTime  %@",timeStr);
}

#pragma mark - UI
- (void)initUI {
    
    self.formTableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    NSMutableArray *items = [NSMutableArray array];
    
    SWFormItem *businessTypeItem = [SWFormItem sw_itemWithTitle:@"业务类型:" info:@"" itemType:SWFormItemTypeSelect editable:NO required:YES keyboardType:UIKeyboardTypeDefault];
    businessTypeItem.itemSelectCompletion = ^(SWFormItem *item) {
        if (!self.KPIDetailModel) [self selectCommunityWithItem];
    };
    [items addObject:businessTypeItem];
    self.businessTypeItem = businessTypeItem;
    
    SWFormSectionItem *sectionItem = [SWFormSectionItem sw_sectionItem:items];
    [self.mutableItems addObject:sectionItem];
   
    
    
    self.formTableView.tableHeaderView = [self headerView];
    self.formTableView.tableFooterView = [self footerView];
    [self.formTableView layoutIfNeeded];
    
}


/**
 创建header
 */
- (UIView *)headerView {
    UIView *headView = [[UIView alloc] init];
    UILabel *label = [[UILabel alloc] init];
    label.text = @"温馨提示：请确保您登记的信息真实有效，发现弄虚作假的将记录不良行为。";
    label.textColor = MAIN_TEXT_COLOR;
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:17];
    label.preferredMaxLayoutWidth = SCREEN_WIDTH - 26;
    [headView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(@16);
        make.bottom.right.equalTo(@(-18));
    }];
    CGFloat height = [headView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    CGRect frame = headView.bounds;
    frame.size.height = height;
    headView.frame = frame;
    return headView;
}

/**
 创建footer
 */
- (UIView *)footerView {
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 160)];
    
    UILabel *label = [[UILabel alloc] init];
    
    label.text = @"协会对您填写的信息予以保密,仅作核验备查不作它用。";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:15];
    label.numberOfLines = 0;
    [footer addSubview:label];
    label.hidden = YES;
    self.bottomTipLabel = label;
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@32);
        make.left.equalTo(footer).offset(2 * globelMargin);
        make.right.equalTo(footer).offset(-2 * globelMargin);
    }];
    
    UIButton *submitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    submitButton.backgroundColor = SECONDARY_TEXT_COLOR;
    submitButton.layer.cornerRadius = 8;
    submitButton.layer.masksToBounds = YES;
    [submitButton setTitle:@"提交" forState:UIControlStateNormal];
    [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [submitButton addTarget:self action:@selector(submitButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    [footer addSubview:submitButton];
    submitButton.userInteractionEnabled = NO;
    self.submitButton = submitButton;
    
    [self.submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(label.mas_bottom).offset(globelMargin);
        make.centerX.equalTo(footer);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH * 0.8, 52));
    }];
    
    return footer;
}

- (UIView *)sectionHeaderView {
    UIView *headView = [[UIView alloc] init];
    UILabel *label = [[UILabel alloc] init];
    label.text = @"政府网签买卖合同编号：";
    label.textColor = MAIN_TEXT_COLOR;
    label.numberOfLines = 0;
    label.font = [UIFont systemFontOfSize:17];
    label.preferredMaxLayoutWidth = SCREEN_WIDTH - 26;
    [headView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(@16);
        make.bottom.right.equalTo(@(-18));
    }];
    CGFloat height = [headView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    CGRect frame = headView.bounds;
    frame.size.height = height;
    headView.frame = frame;
    return headView;
}

@end
